<template>
  <el-container>
    <el-aside width="400px" v-show="isCollapsed" class="mr-10px">
      <el-card shadow="hover" class="search">
        <div class="search_title flex items-center justify-center">
          <el-button link style="padding: 0px; margin-left: -6px">
            <img class="mr-8px w-28px h-28px" src="@/assets/imgs/statistics/search.png" />
            <div class="text-20px text-#FFFFFF">项目查询面板</div>
          </el-button>
        </div>
        <!-- 搜索面板 -->
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="px-30px">
          <el-form-item label="时间范围" prop="end_time" class="time_select mt-20px">
            <el-date-picker
              v-model="queryParams.start_time"
              type="date"
              class="!w-120px mb-18px"
              placeholder="开始日期"
              @change="handleQuery"
              :clearable="false"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <div class="mb-18px">至</div>
            <el-date-picker
              v-model="queryParams.end_time"
              type="date"
              class="!w-120px mb-18px"
              placeholder="结束日期"
              @change="handleQuery"
              :clearable="false"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="所属地区" prop="region_num" class="time_select">
            <el-select
              v-model="queryParams.region_num"
              class="!w-160px mb-18px"
              placeholder="请选择所属地区"
              @change="handleQuery"
              placement="bottom"
            >
              <el-option
                v-for="item in areaList"
                :key="item.order"
                :label="item.desc"
                :value="item.order"
              />
            </el-select>
            <div class="search_time" @click="resetQuery">恢复默认</div>
          </el-form-item>
        </el-form>
        <!-- <div class="flex items-center justify-center mb-10px">
          <div class="text-13px text-#9A9A9A">点击进行项目精准筛选</div>
          <el-icon color="#9A9A9A" :size="16"><CaretBottom /></el-icon>
        </div> -->
        <div class="search_list">
          <div
            v-for="(item, index) in list"
            :key="index"
            title="查看详情"
            class="search_cont"
            @click="goDetail(item)"
          >
            <el-progress
              :width="50"
              class="mx-8px"
              type="circle"
              :percentage="item.progress"
              :color="colors"
            />
            <div class="text-14px text-#222222 mr-10px" style="flex: 1 1">
              <div class="text-16px ellipsis_name">{{ item.project_name }}</div>
              <div class="text-#9A9A9A flex items-center justify-between my-4px">
                <div
                  >项目编码：<span class="text-#222222">{{ item.project_code }}</span></div
                >
                <div
                  >项目阶段：<span class="text-#222222">{{ item.stage }}</span></div
                >
              </div>
              <div class="text-#9A9A9A flex items-center justify-between my-4px">
                <div
                  >承担部门：<span class="text-#222222">{{ item.execute_region }}</span></div
                >
                <div
                  >合同额：<span class="text-#222222">{{ item.amount }}元</span></div
                >
              </div>
              <div class="text-#9A9A9A flex items-center justify-between">
                <div
                  >交付经理：<span class="text-#222222">{{
                    !item.construction_project_manager ? '--' : item.construction_project_manager
                  }}</span></div
                >
                <div class="text-#1684FC"
                  >{{ item.project_receive_time }}<span class="ml-4px">创建</span></div
                >
              </div>
            </div>
          </div>
          <div v-if="list.length === 0 && loading === false">
            <el-empty style="padding: 70px 0" description="暂无内容" />
          </div>
        </div>
      </el-card>
    </el-aside>
    <el-container>
      <div class="right_content">
        <div
          ref="bgRef"
          class="bg flex items-center justify-between"
          :class="{ bg_width: bgWidth < 365 }"
        >
          <div class="ml-3%">
            <div class="flex items-center mb-10px">
              <el-button
                link
                type="primary"
                class="mt-3px"
                @click="toggleCollapse"
                :title="isCollapsed ? '折叠' : '展开'"
              >
                <el-icon v-if="isCollapsed" color="#FFFFFF" :size="24"><Fold /></el-icon>
                <el-icon v-else color="#FFFFFF" :size="24"><Expand /></el-icon>
              </el-button>
              <div class="bg_title ellipsis_name" title="项目综合分析视图">项目综合分析视图</div>
              <div style="position: relative; height: 30px">
                <img
                  class="mx-10px w-35px h-30px"
                  style="cursor: pointer"
                  src="@/assets/imgs/statistics/phone.png"
                />
                <el-popover
                  :visible="visible"
                  placement="bottom"
                  :width="210"
                  content="您还需要什么类型的分析内容，可以随时联系我们哦~，联系电话：2987483497"
                >
                  <template #reference>
                    <el-button
                      class="m-2 w-35px h-28px"
                      style="
                        position: absolute;
                        left: 9px;
                        top: 0;
                        height: 28px !important;
                        opacity: 0;
                        padding: 0;
                        margin: 0;
                      "
                      @click="visible = !visible"
                    >
                      提示
                    </el-button>
                  </template>
                </el-popover>
              </div>
              <img
                class="w-35px h-30px"
                style="cursor: pointer"
                @click="refreshBtn"
                src="@/assets/imgs/statistics/refresh.png"
              />
            </div>
            <div
              class="bg_text ellipsis_name"
              title="数据驱动项目管理新变革，分析统计开启高效运营新时代"
              >数据驱动项目管理新变革，分析统计开启高效运营新时代</div
            >
          </div>
          <div class="mr-2%">
            <div class="w-200px" style="position: relative">
              <img class="w-200px h-80px" src="@/assets/imgs/statistics/time.png" />
              <div class="timeNumber">
                <div class="mr-1px">{{ time }}天</div>
                <el-icon color="#4988FF" :size="26"><CaretBottom /></el-icon>
              </div>
              <el-date-picker
                v-model="selectTime"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-100px"
                style="position: absolute; right: 13px; bottom: 10px; opacity: 0"
                :clearable="false"
                type="daterange"
                range-separator=""
                @change="areaChange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </div>
        </div>
        <el-card shadow="never">
          <el-row :gutter="10" justify="space-between">
            <el-col :span="24">
              <div>
                <div class="mt-1px" style="position: absolute; top: 0px; z-index: 2">
                  <div class="desc_title">当前数据来源</div>
                  <el-select
                    v-model="area"
                    class="!w-120px area_select"
                    placeholder="请选择数据来源"
                    @change="areaChange"
                    placement="right-start"
                    style="position: absolute; top: 4px; z-index: 2; left: 125px"
                  >
                    <el-option
                      v-for="item in areaList"
                      :key="item.order"
                      :label="item.desc"
                      :value="item.order"
                    />
                  </el-select>
                  <div class="desc_cont mb-20px">
                    <img class="w-40px h-40px mx-15px" src="@/assets/imgs/statistics/total.png" />
                    <div>
                      <div class="text-14px mb-3px text-#363636">单个项目最大合同额</div>
                      <div class="text-16px text-#E20000"
                        >¥ {{ singleProjectMaxAmount.amount }}万元</div
                      >
                      <div class="desc_name ellipsis_name text-12px text-#363636">{{
                        singleProjectMaxAmount.projectName
                      }}</div>
                    </div>
                  </div>
                  <div class="desc_cont mb-20px">
                    <img class="w-40px h-40px mx-15px" src="@/assets/imgs/statistics/total.png" />
                    <div>
                      <div class="text-14px mb-3px text-#363636">按计划交付项目数</div>
                      <div class="text-16px text-#E20000"
                        >{{ planDeliveryProjectNum.projectDeliveryNum }}个</div
                      >
                      <div class="desc_name text-12px text-#363636"
                        >平均交付用时：{{ planDeliveryProjectNum.avgDay }}天</div
                      >
                    </div>
                  </div>
                  <div class="desc_cont">
                    <img class="w-40px h-40px mx-15px" src="@/assets/imgs/statistics/total.png" />
                    <div>
                      <div class="text-14px mb-3px text-#363636">项目风险发生频次</div>
                      <div class="text-16px text-#E20000">{{ projectRiskFrequency.riskSum }}次</div>
                      <div class="desc_name ellipsis_name text-12px text-#363636">
                        <span
                          class="risk_style"
                          v-for="item in projectRiskFrequency.riskName"
                          :key="item"
                          >{{ item }}</span
                        >
                      </div>
                    </div>
                  </div>
                </div>
                <div style="position: relation">
                  <MapShaanXi :key="mapKey" :cityType="cityType" :cityData="cityData" />
                </div>
              </div>
            </el-col>
            <el-col :xl="12" :lg="currentType === 1 ? 12 : 24" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px h-600px">
                <div class="flex items-center justify-between">
                  <el-button link style="padding: 0px; margin-left: 14px; position: relative">
                    <div class="title_logo text-16px lh-20px text-#000000">项目类型</div>
                  </el-button>
                </div>
                <Echart :options="pieTypeData" :height="300" />
                <el-table
                  :data="typeTableData"
                  empty-text="暂无记录"
                  stripe
                  :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
                  show-overflow-tooltip
                  :summary-method="getSummaries"
                  show-summary
                  max-height="240"
                >
                  <el-table-column align="center" label="序号" type="index" min-width="100" />
                  <el-table-column align="center" label="类型" prop="type" min-width="160" />
                  <el-table-column align="center" label="项目个数" prop="count" min-width="100" />
                  <el-table-column
                    align="center"
                    label="占比(%)"
                    fixed="right"
                    prop="percentage"
                    width="100"
                  >
                    <template #default="scope">
                      <div>
                        {{ scope.row.percentage }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
            <el-col :xl="12" :lg="currentType === 1 ? 12 : 24" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="h-600px mb-10px">
                <div ref="stageRef" class="flex items-center justify-between">
                  <el-button link style="padding: 0px; margin-left: 14px; position: relative">
                    <div class="title_logo text-16px lh-20px text-#000000">项目阶段</div>
                  </el-button>
                </div>
                <Echart class="stageCont" :options="pieStageData" :height="300" />
                <!-- <Echart :options="pieStageData" :height="200" v-if="stageTableData.length !== 0" />
                    <div v-else class="h-200px">
                      <el-empty style="padding: 10px 0" description="暂无数据" />
                    </div> -->
                <el-table
                  :data="stageTableData"
                  empty-text="暂无记录"
                  stripe
                  :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
                  show-overflow-tooltip
                  :summary-method="getSummaries"
                  show-summary
                  max-height="240"
                >
                  <el-table-column align="center" label="序号" type="index" width="70" />
                  <el-table-column align="center" label="阶段" prop="stage" min-width="120">
                    <template #default="scope">
                      <div> {{ StageObj[scope.row.stage] }} </div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="项目个数" prop="count" min-width="100" />
                  <el-table-column
                    align="center"
                    label="占比(%)"
                    fixed="right"
                    prop="percentage"
                    width="100"
                  >
                    <template #default="scope">
                      <div> {{ scope.row.percentage }} </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
            <el-col :span="24">
              <el-card
                shadow="hover"
                class="mb-10px"
                :class="currentType === 1 ? 'h-800px' : 'h-1100px'"
              >
                <div class="flex items-center justify-between">
                  <el-button link style="padding: 0px; margin-left: 14px; position: relative">
                    <div class="title_logo text-16px lh-20px text-#000000">资金情况</div>
                  </el-button>
                  <el-button link type="primary">
                    <div
                      class="time_change mr-20px"
                      :class="{ time_checked: typeChecked }"
                      :checked="typeChecked"
                      @click="getYearChange"
                      >按年</div
                    >
                    <div
                      class="time_change mr-4px"
                      :class="{ time_checked: !typeChecked }"
                      :checked="!typeChecked"
                      @click="getMonthChange"
                      >按月</div
                    >
                  </el-button>
                </div>
                <Echart
                  :options="barProjectData"
                  :height="450"
                  v-if="totalTableData.length !== 0"
                />
                <div v-else class="h-500px">
                  <el-empty style="padding: 120px 0" description="暂无数据" />
                </div>
                <el-row :gutter="10" justify="space-between">
                  <el-col
                    :xl="12"
                    :lg="currentType === 1 ? 12 : 24"
                    :md="24"
                    :sm="24"
                    :xs="24"
                    :class="currentType === 1 ? 'mb-0px' : 'mb-20px'"
                  >
                    <div class="text-16px text-#303030 text-center font-550 my-8px"
                      >单个项目合同额排名TOP5</div
                    >
                    <el-table
                      :data="totalTableData"
                      empty-text="暂无记录"
                      stripe
                      :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
                      max-height="260"
                    >
                      <el-table-column align="center" label="排名" width="100">
                        <template #default="scope">
                          <div>
                            <el-image class="w-20px h-30px" :src="imgList[scope.$index].img_url" />
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        label="项目名称"
                        prop="project_name"
                        show-overflow-tooltip
                        min-width="160"
                      />
                      <el-table-column
                        align="center"
                        label="总金额（万）"
                        prop="amount"
                        min-width="120"
                      />
                      <el-table-column align="center" label="地市" prop="region" min-width="100" />
                      <el-table-column align="center" label="操作" fixed="right" width="80">
                        <template #default="scope">
                          <el-button link type="primary" @click="goDetail(scope.row)"
                            >查看</el-button
                          >
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                  <el-col :xl="12" :lg="currentType === 1 ? 12 : 24" :md="24" :sm="24" :xs="24">
                    <div class="text-16px text-#303030 text-center font-550 my-8px">{{
                      area === 1 ? '全部地市合同排名' : '全部交付经理合同排名'
                    }}</div>
                    <el-table
                      :data="cityTableData"
                      empty-text="暂无记录"
                      stripe
                      :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
                      show-overflow-tooltip
                      max-height="240"
                    >
                      <el-table-column align="center" label="排名" type="index" min-width="100" />
                      <el-table-column
                        align="center"
                        :label="area === 1 ? '地市' : '交付经理'"
                        prop="name"
                        min-width="160"
                      />
                      <el-table-column
                        align="center"
                        label="总额（万）"
                        prop="amount"
                        min-width="120"
                      />
                      <el-table-column
                        align="center"
                        label="占比"
                        fixed="right"
                        prop="percentage"
                        width="100"
                      >
                        <template #default="scope">
                          <div class="text-#256AF5"> {{ scope.row.percentage }}% </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
            <el-col :span="24">
              <el-card shadow="hover" class="h-600px">
                <div class="flex items-center justify-between">
                  <el-button link style="padding: 0px; margin-left: 14px; position: relative">
                    <div class="title_logo text-16px lh-20px text-#000000">项目处理及时率分析</div>
                  </el-button>
                  <!-- <el-button link type="primary" class="todo_center" @click="goMyRisk">
                      <div class="text-14px text-#6C6C6C">查看更多>></div>
                    </el-button> -->
                </div>
                <el-row :gutter="10" justify="space-between">
                  <el-col :xl="6" :lg="currentType === 1 ? 6 : 12" :md="12" :sm="12" :xs="12">
                    <div class="timely_cont items-center" style="flex-flow: row">
                      <img
                        class="w-50px h-50px ml-8px mr-20px"
                        src="@/assets/imgs/statistics/total.png"
                      />
                      <div class="text-14px text-#222222 mr-10px" style="flex: 1 1">
                        <div class="text-16px ellipsis_name" title="项目总数（个）"
                          >项目总数（个）</div
                        >
                        <div class="text-28px mt-10px" :title="timelyCount">{{ timelyCount }}</div>
                      </div>
                    </div>
                  </el-col>
                  <el-col :xl="6" :lg="currentType === 1 ? 6 : 12" :md="12" :sm="12" :xs="12">
                    <div class="timely_cont text-center">
                      <div>
                        <div class="timely_title ellipsis_name" title="项目交底确认及时率"
                          >项目交底确认及时率</div
                        >
                        <el-progress
                          :width="80"
                          type="circle"
                          class="my-10px"
                          :percentage="timelyTransfer"
                          color="#1684FC"
                        />
                      </div>
                    </div>
                  </el-col>
                  <el-col :xl="6" :lg="currentType === 1 ? 6 : 12" :md="12" :sm="12" :xs="12">
                    <div class="timely_cont text-center">
                      <div>
                        <div class="timely_title ellipsis_name" title="项目内验完成及时率"
                          >项目内验完成及时率</div
                        >
                        <el-progress
                          :width="80"
                          type="circle"
                          class="my-10px"
                          :percentage="timelyDelivery"
                          color="#FFBF6B"
                        />
                      </div>
                    </div>
                  </el-col>
                  <el-col :xl="6" :lg="currentType === 1 ? 6 : 12" :md="12" :sm="12" :xs="12">
                    <div class="timely_cont text-center">
                      <div>
                        <div class="timely_title ellipsis_name" title="项目售中合规率"
                          >项目售中合规率</div
                        >
                        <el-progress
                          :width="80"
                          type="circle"
                          class="my-10px"
                          :percentage="timelySales"
                          color="#A871FF"
                        />
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <div class="text-16px text-#303030 text-center font-550 my-8px"
                  >未及时处理项目列表</div
                >
                <el-table
                  :data="timelyTableData"
                  empty-text="暂无记录"
                  stripe
                  :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
                  show-overflow-tooltip
                  max-height="360"
                >
                  <el-table-column align="center" label="序号" type="index" width="70" />
                  <el-table-column
                    align="center"
                    label="项目名称"
                    prop="project_name"
                    min-width="120"
                  />
                  <el-table-column align="center" label="类型" prop="type" min-width="100" />
                  <el-table-column align="center" label="地市" prop="region" min-width="100" />
                  <el-table-column align="center" label="处理人" prop="deal_user" min-width="100">
                    <template #default="scope">
                      <div class="text-#256AF5">
                        <!-- {{ scope.row.deal_user }} -->
                        {{ !scope.row.deal_user ? '--' : scope.row.deal_user }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="处理延时（天）"
                    prop="deal_delay"
                    min-width="100"
                  />
                  <el-table-column align="center" label="操作" fixed="right" width="80">
                    <template #default="scope">
                      <el-button link type="primary" @click="goDetail(scope.row)">查看</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import * as IctApi from '@/api/project/ict'
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { pieTypeOptions, pieStageOptions, barTimeOptions } from './echarts-data'
import { CaretBottom } from '@element-plus/icons-vue'
import { Fold } from '@element-plus/icons-vue'
import { Expand } from '@element-plus/icons-vue'
import MapShaanXi from './components/map.vue'
import amountImg1 from '@/assets/imgs/statistics/pt1.png'
import amountImg2 from '@/assets/imgs/statistics/pt2.png'
import amountImg3 from '@/assets/imgs/statistics/pt3.png'
import amountImg4 from '@/assets/imgs/statistics/pt4.png'
import amountImg5 from '@/assets/imgs/statistics/pt5.png'

const { push } = useRouter()

const visible = ref(false)

//项目面板折叠与展开
const isCollapsed = ref(true)
const isAutoCollapsed = ref(false) // 自动收缩标志
const mapKey = ref(0) //触发地图更新的键

// 根据窗口大小初始化isCollapsed
const initializeCollapsedState = () => {
  const windowSize = window.innerWidth
  isAutoCollapsed.value = windowSize > 1150
  if (!isAutoCollapsed.value) {
    ElMessage.warning('当前屏幕过小，项目面板已折叠，查看请点击展开按钮，建议缩小屏幕')
  }
  isCollapsed.value = isAutoCollapsed.value
}

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  window.dispatchEvent(new Event('resize'))
  mapKey.value += 1
}

const queryFormRef = ref()

const queryParams = reactive({
  region_num: 12,
  start_time: getStartTime(),
  end_time: getEndOfToday()
})
// 一年前
function getStartTime() {
  const now = new Date()
  const yearAgo = new Date(now)
  yearAgo.setFullYear(yearAgo.getFullYear() - 1)
  // 在 yearAgo 的基础上增加三天
  yearAgo.setDate(yearAgo.getDate() + 3)
  // 设置时间为当天的开始时间
  yearAgo.setHours(0, 0, 0, 0)
  // 格式化为 YYYY-MM-DD HH:mm:ss
  return yearAgo.toISOString().split('T')[0] + ' 00:00:00'
}
//当天日期的最后一秒
function getEndOfToday() {
  let now = new Date()
  now.setHours(23, 59, 59, 999)
  return now.toISOString().split('T')[0] + ' 23:59:59' // 格式化为 YYYY-MM-DD HH:mm:ss
}

const loading = ref(true) // 加载中
const colors = [
  { color: '#5087EC', percentage: 81 },
  { color: '#EE752F', percentage: 100 },
  { color: '#58A55C', percentage: 110 }
]
// 查询面板列表
const list = ref([])
const getProjectPanel = async () => {
  IctApi.getProjectPanel(queryParams)
    .then((res) => {
      list.value = res || []
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 搜索按钮操作
const handleQuery = async () => {
  getProjectPanel()
}

// 恢复默认按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.start_time = getStartTime()
  queryParams.end_time = getEndOfToday()
  getProjectPanel()
}

//地图区域
//根据我的权限角色获取我的可选项
const areaList = ref([])
const area = ref(12)
const selectTime = ref([getStartTime(), getEndOfToday()])
const time = ref(365)
const getAreaList = async () => {
  areaList.value = []
  const data = await IctApi.getRoleSelect()
  areaList.value = data
}
const projectRiskFrequency = ref({})

const planDeliveryProjectNum = ref({})

const singleProjectMaxAmount = ref({})

const cityType = ref(12)
const cityData = ref({})
const areaChange = async () => {
  time.value = getTime(selectTime.value[0], selectTime.value[1])
  cityType.value = area.value
  const params = {
    region_num: area.value,
    start_time: selectTime.value[0],
    end_time: selectTime.value[1]
  }
  const res = await IctApi.getAreaNumber(params)
  if (res.projectAmountSumByRegion) {
    cityData.value.projectAmountSumByRegion = res.projectAmountSumByRegion
    cityData.value.projectSumByRegion = res.projectSumByRegion
  } else {
    cityData.value.projectAmountSumByRegion = {
      宝鸡分公司: '0.0',
      商洛分公司: '0.0',
      西安分公司: '0.0',
      安康分公司: '0.0',
      汉中分公司: '0.0',
      榆林分公司: '0.0',
      延安分公司: '0.0',
      铜川分公司: '0.0',
      咸阳分公司: '0.0',
      渭南分公司: '0.0'
    }
    cityData.value.projectSumByRegion = {
      宝鸡分公司: 0,
      商洛分公司: 0,
      西安分公司: 0,
      安康分公司: 0,
      汉中分公司: 0,
      榆林分公司: 0,
      延安分公司: 0,
      铜川分公司: 0,
      咸阳分公司: 0,
      渭南分公司: 0
    }
  }

  if (res.singleProjectMaxAmount) {
    singleProjectMaxAmount.value = res.singleProjectMaxAmount
  } else {
    singleProjectMaxAmount.value = { amount: '0', projectName: '' }
  }
  if (res.planDeliveryProjectNum) {
    planDeliveryProjectNum.value = res.planDeliveryProjectNum
  } else {
    planDeliveryProjectNum.value = { projectDeliveryNum: '0', avgDay: '0' }
  }
  if (res.projectRiskFrequency) {
    projectRiskFrequency.value = res.projectRiskFrequency
  } else {
    projectRiskFrequency.value = { riskSum: '0', riskName: [] }
  }
  getTotalData()
}

// 计算两个日期之间的天数差
function getTime(startTime, endTime) {
  const date1 = new Date(startTime)
  const date2 = new Date(endTime)
  const diffInMilliseconds = Math.abs(date2 - date1)
  const oneDayInMilliseconds = 24 * 60 * 60 * 1000
  return Math.round(diffInMilliseconds / oneDayInMilliseconds)
}

const dataObj = ref({})

//获取统计数据
const getTotalData = async () => {
  try {
    const params = {
      region_num: area.value,
      start_time: selectTime.value[0],
      end_time: selectTime.value[1]
    }
    const data = await IctApi.getAreaDetail(params)
    dataObj.value = data
    if (data.ProjectStageStatistics.length !== 0) {
      dataObj.value.ProjectStageStatistics = data.ProjectStageStatistics
    } else {
      dataObj.value.ProjectStageStatistics = [
        {
          stage: 'execute_progress',
          count: 0,
          percentage: 0
        },
        {
          stage: 'project_delivery',
          count: 0,
          percentage: 0
        },
        {
          stage: 'team_formation',
          count: 0,
          percentage: 0
        },
        {
          stage: 'test_run',
          count: 0,
          percentage: 0
        },
        {
          stage: 'post_evaluation',
          count: 0,
          percentage: 0
        },
        {
          stage: 'audit',
          count: 0,
          percentage: 0
        },
        {
          stage: 'project_startup',
          count: 0,
          percentage: 0
        },
        {
          stage: 'finished',
          count: 0,
          percentage: 0
        },
        {
          stage: 'project_grading',
          count: 0,
          percentage: 0
        },
        {
          stage: 'project_transfer',
          count: 0,
          percentage: 0
        }
      ]
    }
    getStageData()
    getTypeData()
    isLosk.value = true
    getYearChange()
    getTimelyTable()
  } catch {}
}
// 获取不同阶段的项目数量统计数据

const stageTableData = ref([]) // 项目阶段列表数据
//项目阶段映射
const StageObj = {
  audit: '项目审计',
  execute_progress: '实施进度',
  finished: '已结束',
  post_evaluation: '后评估',
  project_delivery: '项目交付',
  project_grading: '项目定级',
  project_transfer: '项目移交',
  project_startup: '开工填报',
  team_formation: '团队组建',
  test_run: '试运行'
}
const getStageList = ref() //饼图数据

const getStageData = () => {
  stageTableData.value = dataObj.value.ProjectStageStatistics
  getStageList.value = dataObj.value.ProjectStageStatistics
  getPieStageList()
}

// 项目阶段饼图
const pieStageData = reactive<EChartsOption>(pieStageOptions) as EChartsOption
const getPieStageList = async () => {
  pieStageData!.series![0].data = getStageList.value.map((v) => {
    return {
      name: StageObj[v.stage],
      value: v.count
    }
  })
}

// 监听屏幕尺寸
const currentType = ref(1)
const bgRef = ref<HTMLDivElement | null>(null)
let bgWidth = ref(0)
const stageRef = ref<HTMLDivElement | null>(null)
let stageWidth = ref(0)

const handleResize = async () => {
  // 获取当前窗口的宽度（屏幕尺寸）
  const windowSize = window.innerWidth
  if (windowSize >= 1290) {
    currentType.value = 1
  } else {
    currentType.value = 2
  }
  // 确保 DOM 更新完成
  await nextTick()
  updateBgWidth()
  updateStageWidth()
}

//更新背景图宽度
const updateBgWidth = () => {
  if (bgRef.value) {
    bgWidth.value = bgRef.value.offsetWidth
  }
}

//更新阶段饼图图宽度
const updateStageWidth = () => {
  if (stageRef.value) {
    stageWidth.value = stageRef.value.offsetWidth
  }
  if (stageWidth.value < 400) {
    set(pieStageData, 'legend', {
      top: 15,
      width: 'auto',
      left: 'center',
      itemWidth: 20,
      icon: 'circle'
    })
    pieStageData!.series![0].radius = '45%'
    pieStageData!.series![0].center = ['50%', '64%']
  } else {
    set(pieStageData, 'legend', {
      top: 15,
      left: 'center',
      width: '430px',
      itemWidth: 20,
      icon: 'circle'
    })
    pieStageData!.series![0].radius = '50%'
    pieStageData!.series![0].center = ['50%', '59%']
  }
}

const getSummaries = (param) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { color: '#256AF5' } }, ['总计'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = h('div', { style: { color: '#256AF5' } }, [
        `${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)}`
      ])
    }
    // else {
    // sums[index] = h('div', { style: { color: '#256AF5' } }, ['--'])
    // }
  })
  return sums
}

// 获取不同类型的项目数量统计数据
const typeTableData = ref([]) // 项目阶段列表数据
// 项目类型映射
const getTypeList = ref() //饼图数据
const getTypeData = async () => {
  typeTableData.value = dataObj.value.ProjectTypeStatistics
  getTypeList.value = dataObj.value.ProjectTypeStatistics
  getPieTypeList()
}

// 项目类型饼图
const pieTypeData = reactive<EChartsOption>(pieTypeOptions) as EChartsOption
const getPieTypeList = async () => {
  pieTypeData!.series![0].data = getTypeList.value.map((v) => {
    return {
      name: v.type,
      value: v.count
    }
  })
}

//点击切换按年统计
const typeChecked = ref(true)
const isLosk = ref(true)
const totalTableData = ref([]) // 单个项目合同总额排名TOP5表格数据
const cityTableData = ref([]) // 全部地市合同总额排名表格数据
const getYearChange = () => {
  typeChecked.value = true
  if (isLosk.value) {
    getProjectNumberData('year')
    isLosk.value = false
  }
}

//点击切换按月统计
const getMonthChange = () => {
  typeChecked.value = false
  if (!isLosk.value) {
    getProjectNumberData('month')
    isLosk.value = true
  }
}

// 项目金额统计数据
const barProjectList = ref([]) //已结项总额折线图数据
const getProjectNumberData = (type) => {
  totalTableData.value = dataObj.value.SingleProjectContractAmountRank
  cityTableData.value = dataObj.value.AllReginContractAmountRank
  let data
  if (type === 'year') {
    data = dataObj.value.CapitalSituationByYear
  } else {
    data = dataObj.value.CapitalSituationByMonth
  }
  barProjectList.value = data.sort(sortByName)
  getBarProjectList()
}

// 排序函数
const sortByName = (a, b) => {
  // 将年份和月份分开
  const [yearA, monthA] = a.name.split('-').map(Number)
  const [yearB, monthB] = b.name.split('-').map(Number)
  // 先比较年份，如果年份相同再比较月份
  if (yearA !== yearB) {
    return yearA - yearB
  } else {
    return monthA - monthB
  }
}

//项目数量金额统计折线图
const barProjectData = reactive<EChartsOption>(barTimeOptions) as EChartsOption
const getBarProjectList = async () => {
  set(barProjectData, 'xAxis', {
    type: 'category',
    data: barProjectList.value.map((v) => v.name),
    show: true
  })
  set(barProjectData, 'series', [
    {
      name: '合同总额',
      type: 'line',
      data: barProjectList.value.map((v) => v.contract_amount),
      smooth: true,
      areaStyle: {
        color: 'rgba(37,106,245, 0.2)'
      },
      itemStyle: {
        color: 'rgba(37,106,245, 0.8)'
      },
      tooltip: {
        valueFormatter: function (value) {
          return value + '  万'
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}万'
      }
    },
    {
      name: '已结项总额',
      type: 'line',
      data: barProjectList.value.map((v) => v.project_completed_amount),
      smooth: true,
      areaStyle: {
        color: 'rgba(100,149,237, 0.2)'
      },
      itemStyle: {
        color: 'rgba(100,149,237, 0.8)'
      },
      tooltip: {
        valueFormatter: function (value) {
          return value + '  万'
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}万'
      }
    }
  ])
}

// 资金总金额排名图片
const imgList = [
  {
    img_url: amountImg1
  },
  {
    img_url: amountImg2
  },
  {
    img_url: amountImg3
  },
  {
    img_url: amountImg4
  },
  {
    img_url: amountImg5
  }
]

// 跳转风险清单
// const goMyRisk = () => {
//   push({
//     name: 'RiskList'
//   })
// }

// 跳转项目详情
const goDetail = (row) => {
  push({
    name: 'ProjectDetails',
    query: {
      project_code: row.project_code
    }
  })
}

// 项目处理及时率分析
const timelyTableData = ref([]) // 未及时处理项目列表表格数据
const timelyCount = ref('') // 项目总数
const timelyTransfer = ref(0) // 项目交底确认及时率
const timelyDelivery = ref(0) // 项目内验完成及时率
const timelySales = ref(0) // 项目售中合规率
const getTimelyTable = async () => {
  timelyTableData.value = dataObj.value.NotHandledInTimely
  timelyCount.value = dataObj.value.ProjectCount
  timelyDelivery.value = dataObj.value.ProjectTimelinessRateAnalyze.delivery_timely_rate || 0
  timelySales.value = dataObj.value.ProjectTimelinessRateAnalyze.sales_compliance_rate || 0
  timelyTransfer.value = dataObj.value.ProjectTimelinessRateAnalyze.transfer_timely_rate || 0
}

// 刷新
const refreshBtn = () => {
  selectTime.value = [getStartTime(), getEndOfToday()]
  area.value = 12
  resetQuery()
  areaChange()
  getAreaList()
  ElMessage.success('刷新成功！')
}

// 初始化
onMounted(async () => {
  getProjectPanel()
  areaChange()
  getAreaList()
  initializeCollapsedState()
  // 确保 DOM 更新完成
  await nextTick()
  updateBgWidth()
  updateStageWidth()
  handleResize()
  window.dispatchEvent(new Event('resize'))
  // 监听窗口大小变化事件
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.search {
  position: fixed;
  width: 400px;
  box-sizing: border-box;
  height: calc(100vh - 105px);
}

.right_content {
  flex: 1;
  overflow-x: hidden;
  box-sizing: border-box;
}

:deep(.el-card__body) {
  padding: 10px;
}
.bg {
  width: 100%;
  height: 110px;
  background: url(/@/assets/imgs/statistics/bg.png) no-repeat;
  background-size: 100% 100%;
  color: rgba(255, 255, 255, 1);
  font-size: 20px;
}

.bg_title {
  color: rgba(255, 255, 255, 1);
  font-size: 28px;
  text-align: left;
  font-family: FZZongYi-regular;
}

.bg_text {
  height: 20px;
  line-height: 19px;
  border-radius: 7px;
  color: #0242a5;
  font-size: 14px;
  padding: 0 10px;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.5) 40%);
}

.desc_title {
  max-width: 300px;
  height: 40px;
  line-height: 40px;
  border-radius: 5px;
  color: rgb(40, 39, 39);
  font-size: 18px;
  margin-bottom: 20px;
}

.desc_cont {
  max-width: 300px;
  height: 80px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  background: linear-gradient(
    88.34deg,
    rgba(227, 239, 255, 1) 1.05%,
    rgba(227, 239, 239, 0) 98.31%
  );
}

.timeNumber {
  position: absolute;
  right: 12px;
  bottom: 11px;
  width: 103px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgb(16, 16, 16);
  font-size: 18px;
}

.risk_style {
  border-right: 1px solid #363636;
  padding-right: 5px;
  padding-left: 5px;
}

.risk_style:last-child {
  border-right: none;
}

.risk_style:first-child {
  padding-left: 0px;
}

.search :deep(.el-card__body) {
  padding: 0px;
}

.search_title {
  height: 45px;
  position: relative;
  border-radius: 3px;
  background: linear-gradient(
    140.6deg,
    rgba(77, 197, 236, 1) -1.27%,
    rgba(17, 106, 244, 1) 102.17%
  );
}

.search_time {
  width: 90px;
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
  background-color: rgba(46, 124, 246, 1);
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  margin-bottom: 18px;
  text-align: center;
  cursor: pointer;
}

.search_list {
  overflow-y: scroll;
  overflow-x: hidden;
  box-sizing: border-box;
  height: calc(100vh - 275px);
}

.search_list > div:first-child {
  margin-top: 1px;
}

.search_list > div:last-child {
  margin-bottom: 5px;
}

:deep(.search_list)::-webkit-scrollbar {
  width: 4px;
}

:deep(.search_list):hover::-webkit-scrollbar-thumb {
  background: rgba(68, 68, 68, 0.1);
}

:deep(.search_list)::-webkit-scrollbar-thumb {
  border-radius: 20px;
  background: transparent;
}

:deep(.search_list)::-webkit-scrollbar-track {
  display: none;
}

.search_cont {
  display: flex;
  overflow-x: visible;
  overflow-y: hidden;
  align-items: center;
  cursor: pointer;
  width: 98%;
  margin-left: 1%;
  margin-bottom: 10px;
  padding-top: 10px;
  padding-bottom: 10px;
  min-height: 92px;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 6px 0px rgba(190, 190, 190, 0.4);
}

:deep(.el-progress__text) {
  font-size: 12px !important;
  font-weight: 550;
  color: #222222;
}

.title_logo::after {
  content: '';
  position: absolute;
  left: -14px;
  top: -3px;
  width: 7px;
  height: 25px;
  line-height: 25px;
  border-radius: 5px;
  background: linear-gradient(90.69deg, rgba(98, 172, 255, 1) 1.35%, rgba(68, 130, 255, 1) 99.38%);
}

.time_checked {
  background-color: #256af5 !important;
  color: rgba(255, 255, 255, 1) !important;
}

.time_change {
  width: 80px;
  height: 26px;
  line-height: 26px;
  border-radius: 9px;
  background-color: rgba(255, 255, 255, 1);
  color: rgba(46, 124, 246, 1);
  font-size: 14px;
  text-align: center;
  border: 2px solid rgba(46, 124, 246, 1);
  margin-top: 2px;
  cursor: pointer;
}

.ellipsis_name {
  overflow: hidden;
  display: -webkit-box;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

.area_select :deep(.el-select__wrapper) {
  font-size: 16px;
}

.area_select :deep(.el-select__placeholder) {
  padding-bottom: 1px;
}

.time_select {
  width: 100% !important;
  margin-right: 0px !important;
  margin-bottom: 0px;
}
:deep(.el-form-item__content) {
  justify-content: space-between !important;
}

.timely_cont {
  min-height: 140px;
  margin-bottom: 10px;
  margin-top: 10px;
  display: flex;
  flex-flow: column;
  justify-content: space-evenly;
}

.timely_title {
  height: 40px;
  line-height: 40px;
  background: linear-gradient(180deg, rgba(225, 235, 255, 1) 0%, rgba(255, 255, 255, 0) 100%);
  color: rgba(16, 16, 16, 1);
  font-size: 16px;
  text-align: center;
}

.bg_width {
  display: block !important;
  height: 149px !important;
}
</style>